package hiatao.puzzle.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.daimajia.androidanimations.MyActivity;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.nineoldandroids.animation.Animator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.pingplusplus.android.PingppLog;
import com.pingplusplus.libone.PaymentHandler;
import com.pingplusplus.libone.PingppOne;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import haitao.dialog.view.MaterialDialog;
import haitao.puzzle.R;
import hiatao.puzzle.game.view.GamePintuLayout;
import hiatao.puzzle.game.view.GamePintuLayout.OnPlayGameListener;
import hiatao.puzzle.utils.ImageUtils;
import hiatao.puzzle.utils.PixelUtil;
import hiatao.puzzle.utils.StatusBarCompat;
import hiatao.puzzle.utils.Tools;

public class PuzzleGameActivity extends FragmentActivity implements OnClickListener,
		OnPlayGameListener , PaymentHandler {

	private static String URL = "http://218.244.151.190/demo/charge";
	private ImageView img;
	private ImageView head_img;
	private ImageView small_img;
	private ImageView btn_rank;
	private ImageView btn_more;
	private View top_back;
	private TextView intro_tv;
	private TextView bushu_tv;
	private TextView title_tv;
	private View tanmu1;
	private View tanmu2;
	private View tanmu3;
	private View follow_tv;
	private View sixin_tv;
	private View pop_view;
	// private TextView model_tv;
	private Chronometer time_chr;
	private String url;
	private GamePintuLayout mGameView;
	private int height = 0;
	private int type = 0;
	private YoYo.YoYoString rope;
	private boolean finish;
	MaterialDialog mMaterialDialog;
	MaterialDialog mMaterialDialog2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game);
		findView();
		init();
		StatusBarCompat.compat(this, getResources().getColor(R.color.primary));
	}

	private void init() {
		LayoutParams lp = (LayoutParams) img.getLayoutParams();
		height = PixelUtil.getScreenWidth(this) - PixelUtil.dp2px(this, 20);
		lp.height = height;
		lp.width = height;
		img.setLayoutParams(lp);
		LayoutParams lp2 = (LayoutParams) mGameView.getLayoutParams();
		lp2.height = height;
		lp2.width = height;
		mGameView.setLayoutParams(lp2);

		url = getIntent().getStringExtra("URL");
		ImageUtils.loadImg(getIntent().getStringExtra("HEADURL"), head_img);
		title_tv.setText(getIntent().getStringExtra("NAME"));
		intro_tv.setText(getIntent().getStringExtra("INTRO"));
		ImageUtils.loadImg(url, img);
		ImageUtils.loadImg(url, small_img);
		top_back.setOnClickListener(this);

		type = Tools.getRandom(3, 5);
		/*
		 * if(type==3){ model_tv.setText("3x3"); }else if(type ==4){
		 * model_tv.setText("4x4"); }else{ model_tv.setText("5x5"); }
		 */
		toGame();
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				tanmuAnim(tanmu2, 5200);
			}
		}, 200);
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				tanmuAnim(tanmu1, 5200);
			}
		}, 1500);
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				tanmuAnim(tanmu3, 5200);
			}
		}, 2000);
	 	mMaterialDialog = new MaterialDialog(this);
	 	mMaterialDialog2 = new MaterialDialog(this);
		showDialog();

	}
   private void showDialog(){
	   if (mMaterialDialog != null) {
		   mMaterialDialog.setTitle("提示")
				   .setMessage(
						   "挑战成功步数"+" " +(type*2))
				   .setPositiveButton(
						   "OK", new View.OnClickListener() {
							   @Override
							   public void onClick(View v) {
								   Tools.log("PAY-DDDDDDDDD--------------");
								   mMaterialDialog.dismiss();
							   }
						   }
				   )
				   .setNegativeButton(
						   "CANCLE", new View.OnClickListener() {
							   @Override
							   public void onClick(View v) {
								   mMaterialDialog.dismiss();
							   }
						   }
				   )
				   .setCanceledOnTouchOutside(false)
				   .setOnDismissListener(
						   new DialogInterface.OnDismissListener() {
							   @Override
							   public void onDismiss(DialogInterface dialog) {
								   mMaterialDialog.dismiss();
							   }
						   }
				   )
				   .show();
	   }
   }
   private void showPayDialog(){
	   if (mMaterialDialog2 != null) {
		   mMaterialDialog2.setTitle("提示")
				   .setMessage(
						   "挑战失败 支付1元可以继续游戏")
				   .setPositiveButton(
						   "OK", new View.OnClickListener() {
							   @Override
							   public void onClick(View v) {
								   mMaterialDialog2.dismiss();
								   pay();
							   }
						   }
				   )
				   .setNegativeButton(
						   "CANCLE", new View.OnClickListener() {
							   @Override
							   public void onClick(View v) {
								   mMaterialDialog2.dismiss();
							   }
						   }
				   )
				   .show();
	   }
   }

	private  void pay(){
		Tools.log("PAY---------------");
		//设置需要使用的支付方式
		PingppOne.enableChannels(new String[]{"wx", "alipay", "upacp", "bfb", "jdpay_wap"});

		// 提交数据的格式，默认格式为json
		// PingppOne.CONTENT_TYPE = "application/x-www-form-urlencoded";
		PingppOne.CONTENT_TYPE = "application/json";
		PingppLog.DEBUG = true;

		String orderNo = new SimpleDateFormat("yyyyMMddhhmmss")
				.format(new Date());

		// 计算总金额（以分为单位）
		int amount = 100;
		JSONArray billList = new JSONArray();
		billList.put("游戏支付" + " x " +"1");

		// 构建账单json对象
		JSONObject bill = new JSONObject();

		// 自定义的额外信息 选填
		JSONObject extras = new JSONObject();
		try {
			extras.put("extra1", "extra1");
			extras.put("extra2", "extra2");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		try {
			bill.put("order_no", orderNo);
			bill.put("amount", amount);
			bill.put("extras", extras);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		//壹收款: 创建支付通道的对话框
		PingppOne.showPaymentChannels(getSupportFragmentManager(), bill.toString(), URL, this);
	}
	private void tanmuAnim(final View v, final int time) {
		rope = YoYo.with(Techniques.SlideOutLeft).duration(time)
				.interpolate(new AccelerateDecelerateInterpolator())
				.withListener(new Animator.AnimatorListener() {
					@Override
					public void onAnimationStart(Animator animation) {
					}

					@Override
					public void onAnimationEnd(Animator animation) {
						if (!finish)
							tanmuAnim(v, time);
					}

					@Override
					public void onAnimationCancel(Animator animation) {
					}

					@Override
					public void onAnimationRepeat(Animator animation) {

					}
				}).playOn(v);
	}

	private void findView() {
		tanmu1 = findViewById(R.id.tanmu1);
		tanmu2 = findViewById(R.id.tanmu2);
		tanmu3 = findViewById(R.id.tanmu3);
		btn_rank = (ImageView) findViewById(R.id.btn_rank);
		btn_more = (ImageView) findViewById(R.id.btn_more);
		btn_more.setOnClickListener(this);
		btn_rank.setOnClickListener(this);
		img = (ImageView) findViewById(R.id.img);
		head_img = (ImageView) findViewById(R.id.head_img);
		small_img = (ImageView) findViewById(R.id.small_img);
		top_back = findViewById(R.id.top_back);
		intro_tv = (TextView) findViewById(R.id.intro_tv);
		bushu_tv = (TextView) findViewById(R.id.bushu_tv);
		// model_tv = (TextView) findViewById(R.id.model_tv);
		title_tv = (TextView) findViewById(R.id.title_tv);
		time_chr = (Chronometer) findViewById(R.id.time_chr);
		mGameView = (GamePintuLayout) findViewById(R.id.id_gameview);
	}

	private void toGame() {
		mGameView.setVisibility(View.VISIBLE);
		img.setVisibility(View.GONE);
		ImageLoader.getInstance().loadImage(url,
				new SimpleImageLoadingListener() {
					public void onLoadingComplete(String imageUri,
							android.view.View view,
							final android.graphics.Bitmap loadedImage) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								mGameView.setBitmap(loadedImage, height, type);
							}
						});
					};
				});
		mGameView.setPlayGameListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.top_back:
			finish();
			break;
		case R.id.btn_rank:
			Toast.makeText(PuzzleGameActivity.this, "暂无排名", 0).show();
			break;
		case R.id.btn_more:
			showPpw();
			break;
		default:
			break;
		}
	}

	private void showPpw() {
		 pop_view = getLayoutInflater().inflate(R.layout.share_popup_window2, null);

		final PopupWindow popupWindow = new PopupWindow(pop_view,
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		popupWindow.setTouchable(true);
		popupWindow.setOutsideTouchable(true);
		// 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
		// 我觉得这里是API的一个bug
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置好参数之后再show
		popupWindow.showAsDropDown(btn_more, 0, 0);
		follow_tv = pop_view.findViewById(R.id.follow_view);
		sixin_tv = pop_view.findViewById(R.id.sixin_view);
		follow_tv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}

		});
		sixin_tv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			}

		});
	}

	@Override
	public void onMoveNumChange(int num) {
		bushu_tv.setText(num + "");
		if (num==type*2 && !mGameView.isSeccess()){
			// 步数用完了
			mGameView.setStop(true);
			showPayDialog();
		}
	}

	@Override
	public void onSuccess(int num) {
		time_chr.stop();
		showSuccess();
	}

	/**
	 * 显示通知
	 */
	protected void showSuccess() {
		View view = getLayoutInflater().inflate(R.layout.dia_choose, null);
		TextView d_bushu_tv = (TextView) view.findViewById(R.id.bushu_tv);
		TextView time_v = (TextView) view.findViewById(R.id.time_chr);
		time_v.setText(time_chr.getText());
		d_bushu_tv.setText(bushu_tv.getText());
		Dialog dialog = new Dialog(this, R.style.IOSDialog);
		dialog.setContentView(view, new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		dialog.show();
		time_chr.stop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		finish = true;
		time_chr.stop();
	}

	@Override
	public void onstart() {
		time_chr.setBase(SystemClock.elapsedRealtime());
		time_chr.setFormat("%s");
		time_chr.start();
	}
	@Override
	public void onStopPlay() {
         showPayDialog();
	}
	@Override
	public void handlePaymentResult(Intent data) {
		if (data != null) {
			/**
			 * code：支付结果码  -2:服务端错误、 -1：失败、 0：取消、1：成功
			 * error_msg：支付结果信息
			 */
			int code = data.getExtras().getInt("code");
			if (code==1){
				mGameView.setStop(false);
				Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
				if (mMaterialDialog2 != null ) {
					mMaterialDialog2.dismiss();
				}
			}else{
				Toast.makeText(this, "支付失败", Toast.LENGTH_SHORT).show();
			}
			String errorMsg = data.getExtras().getString("error_msg");
		}
	}
}
